<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <crudOperation :permission="permission">
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          @click="crud.toDetail('financeSettlementDetail')"
        >
          新增
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="danger"
          :loading="crud.rejectLoading"
          icon="el-icon-remove-outline"
          @click="audit('PASS','审核')"
          :disabled="crud.selections.length < 1"
          v-permission="permission.pass"
        >
          审核
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          :loading="crud.rejectLoading"
          type="success"
          icon="el-icon-circle-check"
          :disabled="crud.selections.length < 1"
          @click="audit('REJECT','反审')"
          v-permission="permission.reject"
        >
          反审
        </el-button>
        <el-button
          slot="left"
          v-permission="permission.del"
          :disabled="crud.selections.length === 0"
          :loading="crud.delAllLoading"
          class="filter-item"
          size="mini"
          type="danger"
          @click="toDelete(crud.selections)"
        >
          删除
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          @click="exportDetail('\\exportReceiptPaymentDetail')"
        >
          导出收付款详情
        </el-button>
        <el-button
          slot="left"
          class="filter-item"
          size="mini"
          type="primary"
          @click="exportDetail('\\exportOrderDetail')"
        >
          导出单据详情
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="warning"
          icon="el-icon-notebook-2"
          :disabled="crud.selections.length < 1"
          @click="tabInvoiceType('collectPrint',0)"
        >汇总打印</el-button>
      </crudOperation>
      <el-dialog  title="打印预览"
                  destroy-on-close
                  v-dialogDrag
                  close-on-press-escape
                  :visible.sync="showPdf" append-to-body width="50vw">
        <j-pdf :src="pdfSrc" ></j-pdf>
      </el-dialog>
      <div v-if="!crud.props.searchToggle">
        <el-form size="small" label-width="120px" v-formkey="{query:toQuery}">
          <el-row :gutter="10" >
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务日期">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.startTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="开始日期"
                  />
                  <el-date-picker
                    v-model="query.endTime"
                    align="right"
                    unlink-panels
                    class="fl1"
                    format="yyyy - MM - dd "
                    value-format="yyyy-MM-dd"
                    default-value
                    range-separator=""
                    placeholder="结束日期"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="往来单位">
                <zSelect :value.sync="query.customerId" url="api/dropDown/basCustomerList" :params="{businessAttr:'3'}"
                         style="width:  100%"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据编号">
                <el-input v-model="query.code" placeholder="请输入单据编号"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="来源单据编号">
                <el-input v-model="query.sourceCode" placeholder="请输入来源单据编号"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="销售单号">
                <el-input v-model="query.salesOrderCode" placeholder="请输入销售单号"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="收付款单号">
                <el-input v-model="query.receiptPaymentCode" placeholder="请输入收付款单号"/>
              </el-form-item>
            </el-col>
            <el-col span="6">
              <el-form-item label="二批">
                <table-select
                  :tableColumns="
                  [
                  {prop:'code',label:'二批编码',width: '100'},
                  {prop:'name',label:'二批名称',width: '150'},
                  ]"
                  labelKey="name"
                  valueKey="id"
                  width="400"
                  :params="{type:3}"
                  :value.sync="query.sCustomerIds"
                  placeholder="请选择二批"
                  url="api/dropDown/basCustomerList"
                ></table-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="创建人">
                <zSelect :value.sync="createUserIds" multiple url="/api/dropDown/sysUserList" style="width:  100%;"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="备注">
                <el-input v-model="query.remark" placeholder="请输入备注"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据状态">
                <el-select multiple v-model="query.orderStatus" class="edit-input" placeholder="请选择单据状态" style="width: 100%;">
                  <el-option
                    v-for="(item,index) in dict.common_order_status"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="人员">
                <table-select
                  :tableColumns="
                  [
                  {prop:'code',label:'人员编码',width: '100'},
                  {prop:'name',label:'人员名称',width: '150'},
                  ]"
                  labelKey="name"
                  valueKey="id"
                  width="400"
                  :value.sync="query.userIds"
                  placeholder="请选择人员"
                  url="api/dropDown/sysUserList"
                ></table-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="收款人">
                <table-select
                  :tableColumns="
                  [
                  {prop:'code',label:'人员编码',width: '100'},
                  {prop:'name',label:'人员名称',width: '150'},
                  ]"
                  labelKey="name"
                  valueKey="id"
                  width="400"
                  :value.sync="query.payeeUserIds"
                  placeholder="请选择人员"
                  url="api/dropDown/sysUserList"
                ></table-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="出纳">
                <table-select
                  :tableColumns="
                  [
                  {prop:'code',label:'人员编码',width: '100'},
                  {prop:'name',label:'人员名称',width: '150'},
                  ]"
                  labelKey="name"
                  valueKey="id"
                  width="400"
                  :value.sync="query.cashierUserIds"
                  placeholder="请选择人员"
                  url="api/dropDown/sysUserList"
                ></table-select>
              </el-form-item>
            </el-col>
          </el-row>
            <el-row :gutter="10"  style="margin-top: 5px;margin-bottom: 5px">
              <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
                <el-button class="filter-item"  size="mini" type="primary" @click="queryReport">搜索</el-button>
                <el-button class="filter-item" plain   size="mini" type="primary"
                           @click="resetQuery" >重置</el-button>
              </el-col>
          </el-row>
        </el-form>
      </div>
      <!--表格渲染-->
      <el-table
        ref="table"
        @row-click="crud.selectRow"
        v-if="isShowTable"
        @header-dragend="changeColWidth"
        @contextmenu.native="showMenu"
        @sort-change="sortTab"
        :row-style="crud.rowClass"
        :row-class-name="crud.tableRowClassName"
        border
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        @row-dblclick="crud.toDetailPlus('financeSettlementDetail',$event.id)"
        @selection-change="crud.selectionChangeHandler"
        :summary-method="crud.sumRow"
        :height="tableHeight"
        show-summary
      >
        <el-table-column :render-header="crud.renderHeader" type="selection" width="60"/>
        <el-table-column :render-header="crud.renderHeader" type="index" width="60" label="序号"/>
        <el-table-column
          v-if="item.visible"
          v-for="(item, index) in crud.header"
          :key="`col_${index}`"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          :data-porp='item.prop'
          @contextmenu.native="showMenu"
          @header-dragend="changeColWidth"
          :sortable="item.sortable?'custom':false"
          :sort-orders="['descending', 'ascending', null]"
          sort-change="sort"
        >
          <!-- 自定义渲染模版 -->
          <template slot-scope="scope">
            <!-- 当列key为 sort 时，渲染一个手柄icon -->
            <template v-if="item.prop =='sort'">
              <div class="handle_move">
                <i :class="scope.row['sort']" />
              </div>
            </template>
            <template v-else>
              <span v-if="item.type == 1" style="margin-left: 10px">
<!--                <span v-if="item.prop === 'sourceCode'" class="codeJump" @click="jump(scope.row)">-->
<!--                  {{scope.row[`${item.prop}`]}}-->
<!--                </span>-->
                <span v-if="item.prop === 'orderSourceCode'">
                  <span  v-for="(item,index) in getBillCode(scope.row[`${item.prop}`])" @click="jumpSend(scope.row[`orderSourceIds`],scope.row[`orderSourceType`],index,scope.row)" class="codeJump">
                    {{ item }}
                  </span>
                </span>
                <span v-else>
                  {{scope.row[`${item.prop}`]}}
                </span>
              </span>
              <span v-if="item.type == 2" style="margin-left: 10px">{{ parseTime(scope.row[`${item.prop}`])}}</span>
              <span v-if="item.type == 3" style="margin-left: 10px">{{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}</span>
            </template>
          </template>
        </el-table-column>

<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('busDate')" prop="busDate" label="业务日期"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('code')" prop="code" label="单据编号"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('sourceCode')" prop="sourceCode" label="来源单据编号"/>-->
<!--        <el-table-column width="100" v-if="columns.visible('sourceType')" prop="sourceType" label="来源类型">-->
<!--          <template slot-scope="scope">-->
<!--            <span v-for="item in dict.t_finance_settlement_source_type" v-if="item.value == scope.row.sourceType">{{-->
<!--                item.label-->
<!--              }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('bankName')" prop="bankName" label="银行名称"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerCode')" prop="customerCode" label="往来单位编码"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('customerName')" prop="customerName" label="往来单位"/>-->
<!--        <el-table-column width="100px" v-if="columns.visible('sCustomerName')" prop="sCustomerName"-->
<!--                         label="二批"-->
<!--        />-->
<!--        <el-table-column width="100px" v-if="columns.visible('orderSourceCode')" prop="orderSourceCode"-->
<!--                         label="明细单据号"-->
<!--        />-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('cancelAmount')" prop="cancelAmount" label="核销金额"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('taxAmount')" prop="taxAmount" label="收付款金额"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('saleTaxAmount')" prop="saleTaxAmount" label="销售金额"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('saleReturnTaxAmount')" prop="saleReturnTaxAmount" label="销售退货金额金额"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('returnBottleBoxTaxAmount')" prop="returnBottleBoxTaxAmount" label="回箱金额"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('saleBeginTaxAmount')" prop="saleBeginTaxAmount" label="销售期初金额"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('buyTaxAmount')" prop="buyTaxAmount" label="采购金额"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('buyReturnTaxAmount')" prop="buyReturnTaxAmount" label="采购退货金额"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('feeTaxAmount')" prop="feeTaxAmount" label="费用金额"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('buyBeginTaxAmount')" prop="buyBeginTaxAmount" label="采购期初金额"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('buyReturnBeginTaxAmount')" prop="buyReturnBeginTaxAmount" label="采购退货期初金额"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('saleReturnBeginTaxAmount')" prop="saleReturnBeginTaxAmount" label="销售退货初金额"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('orderStatus')" prop="orderStatus" label="状态">-->
<!--          <template slot-scope="scope">-->
<!--            <span v-if="scope.row.orderStatus === 'SAVE'">保存</span>-->
<!--            <span v-if="scope.row.orderStatus === 'PASS'">审核</span>-->
<!--            <span v-if="scope.row.orderStatus === 'CLOSE'">关闭</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-if="columns.visible('remark')" prop="remark" label="备注"/>-->
<!--        <el-table-column :render-header="crud.renderHeader" v-permission="['admin','financeSettlement:edit','financeSettlement:del']" label="操作"-->
<!--                         width="150px" align="center">-->
<!--          <template slot-scope="scope">-->
<!--            <udOperation-->
<!--              :data="scope.row"-->
<!--              :permission="permission"-->
<!--            />-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
      <!--分页组件-->
      <pagination/>
      <vue-context-menu :contextMenuData="contextMenuData"
                        @tableConfig="tableConfig"
                        @deletedata="deletedata"></vue-context-menu>

      <!-- 表格配置 -->
      <el-dialog title="表格配置"
                 :visible.sync="tableConfigShow"
                 width="60%">
        <j-table-column-config :columns.sync="crud.header"  @tabSave="tabSave" @pit="pit" />
      </el-dialog>

      <el-dialog
        title="请选择打印模板"
        :visible.sync="crud.printConfig.pringDialog"
        width="30%"
      >
        <jPrintConfig groupId="financeSettlement"
                      v-if="crud.printConfig.pringDialog"
                      @getPrintId="crud.toPrint"
                      :isPreview="crud.printConfig.isPreview"
        ></jPrintConfig>
      </el-dialog>
      <el-dialog
      title="请选择打印模板"
      :visible.sync="pringDialog"
      width="30%"
    >
      <jPrintConfig groupId="financeSettlement"
                    v-if="pringDialog"
                    @getPrintId="print"
      ></jPrintConfig>
    </el-dialog>
    </div>
  </div>
</template>

<script>
import crudFinanceSettlement from '@/api/erp/financeSettlement'
import CRUD, {crud, header, presenter} from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import jPrintConfig from "../../../components/jPrintConfig/jPrintConfig";
import {tablemixins} from "@/mixins/tablemixins";
import { download } from '@/api/data'
import { downloadFile } from '@/utils'
import { publicListKey } from "@/utils/key"
import {getHeaderProperties} from "@/api/erp/headerProperties";
import  jTableColumnConfig from "@/components/jTableColumnConfig/jTableColumnConfig";


// crud交由presenter持有
const defaultCrud = CRUD({
  title: '单据结算',
  url: 'api/financeSettlement',
  sort: 'id,desc',
  optShow: {
    add: false,
    edit: false,
    del: false,
    print: true,
    printDetail: true,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: false,
    reject: false,
    download: true
  },
  query: {
    dataExtent: null,
    sourceCode: null,
    customerName: null,
    orderStatus: null,
    bankAccount: null,
    userIds:'',
    startTime:new Date().toISOString().split('T')[0],
    endTime:new Date().toISOString().split('T')[0],
  },
  crudMethod: {...crudFinanceSettlement}
})
export default {
  name: 'FinanceSettlement',
  components: {pagination, crudOperation, rrOperation, udOperation,jPrintConfig,jTableColumnConfig,getHeaderProperties},
  mixins: [presenter(defaultCrud), header(), crud(),tablemixins,publicListKey],
  dicts:['t_finance_settlement_source_type','common_order_status'],
  data() {
    return {
      invoiceType: "collectPrint",
      printIds:[],
      pringDialog: false,
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      permission: {
        add: ['admin', 'financeSettlement:add'],
        edit: ['admin', 'financeSettlement:edit'],
        del: ['admin', 'financeSettlement:del'],
        import: ['admin', 'financeSettlement:import'],
        export: ['admin', 'financeSettlement:export'],
        copy: ['admin', 'financeSettlement:copy'],
        upload: ['admin', 'financeSettlement:upload'],
        download: ['admin', 'financeSettlement:download'],
        pass: ['admin', 'financeSettlement:pass'],
        reject: ['admin', 'financeSettlement:reject'],
        closed: ['admin', 'financeSettlement:closed'],
        invalid: ['admin', 'financeSettlement:invalid'],
        stop: ['admin', 'financeSettlement:stop'],
        recover: ['admin', 'financeSettlement:recover'],
      },
      rules: {},
      tableHeight: 0,
      createUserIds: [],
      jumpPath: {
        1:'/buy/buyOrderDetail',
        2:'/fee/feeOrderDetail',
        3:'/buy/buyBegin',
        4:'/sale/salesorderDetail',
        5:'/ware/wareReturnBottleBoxDetail',
        6:'/sale/salesBegin'
      }
    }
  },
  created() {
   this.setTableHeight()


  },
  mounted() {
    window.onresize = () => {
      return (() => {
        this.setTableHeight()
      })();
    };
  },

  watch: {},
  methods: {
    setQuery(id,orderType){
      this.$router.push(this.billType[orderType]+`${this.indexlist.includes(orderType)?'?id=':'/'}`+id)
    },
    jumpSend(ids,types,index,row){
      const idsList = ids.split(',')
      const typesList = types.split(',')
      if (typesList[index] ==='3'||typesList[index]==='6'){
        this.$router.push({path:`${this.jumpPath[typesList[index]] + '?id='  + idsList[index]}`})
      }else {
          this.$router.push({path:`${this.jumpPath[typesList[index]]+'/'+idsList[index]}`})
      }

    },
    getBillCode(ids){
      if (ids){
        return ids.split(',')
      }
    },
    queryReport(){
      this.query.createUserIds = this.createUserIds.length?this.createUserIds.join(','):''
      this.crud.toQuery()
    },
    resetQuery(){
      this.createUserIds = []
      this.query.userIds = null
      this.crud.resetQuery()
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    getValue(e) {
      this.query.startTime = this.query.dataExtent[0]
      this.query.endTime = this.query.dataExtent[1]
    },
    setTableHeight(){
      const ratio =this.getRatio() / 100
      this.tableHeight = (window.screen.height - (200*ratio)) / ratio
    },
    exportDetail(type){
      this.crud.downloadDetailLoading = true
      this.crud.query.orderIds = ''
      this.crud.query.ids = ''
      this.crud.selections.forEach(item => {
        this.crud.query.orderIds += item.id + ','
      })
      console.log(this.crud.selections)
      // const params = this.crud.getQueryParams()
      download(this.crud.url + type, {ids: this.crud.query.orderIds}).then(result => {
        downloadFile(result, this.crud.title + '数据', 'xlsx')
        this.crud.downloadDetailLoading = false
      }).catch(() => {
        this.crud.downloadDetailLoading = false
      })
    },

   getRatio()
        {
          var ratio = 0;
          var screen = window.screen;
          var ua = navigator.userAgent.toLowerCase();

          if (window.devicePixelRatio !== undefined) {
            ratio = window.devicePixelRatio;
          } else if (~ua.indexOf('msie')) {
            if (screen.deviceXDPI && screen.logicalXDPI) {
              ratio = screen.deviceXDPI / screen.logicalXDPI;
            }

          } else if (window.outerWidth !== undefined && window.innerWidth !== undefined) {
            ratio = window.outerWidth / window.innerWidth;
          }

          if (ratio) {
            ratio = Math.round(ratio * 100);
          }
          return ratio;
        },
    toDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (datas.some(item=>item.sourceType !== '1')){
          this.$message.error('只有手动新增的才允许删除')
          return
        }
        this.crud.delAllLoading = true
        this.crud.doDelete(datas)
      }).catch(() => {
      })
    },
    audit(type,msg){
      this.crud.rejectLoading = true
      const ids = this.crud.selections.map(m=>m.id)
      const data = {
        ids:ids,
        type:type
      }
      crudFinanceSettlement.passOrReject(data).then(res=>{
        if(200 === res.status){
          this.crud.refresh()
          this.$message.success(msg+"成功")
        }
        this.crud.rejectLoading = false
      }).catch(e=>{
        this.crud.rejectLoading = false
      })
    },
    tabInvoiceType(val,isPreview){
      this.invoiceType = val
      this.isPreview = isPreview
      this.pringDialog = true;
    },
    print(val){
      if(val !== null){
        this.pringDialog=false
        localStorage.setItem(this.invoiceType,val)
        this.crud.doPrint(val,this.printIds,this.isPreview,this.invoiceType)
      }else {
        this.$message.error('请选择打印模板');
      }
    },
  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
.codeJump{
  color: blue;
  cursor: pointer;
}
</style>
